package com.zzc.keleapiGateway.filter;

import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.zzc.keleapiCommon.model.dto.InterfaceInfoDTO;
import com.zzc.keleapiCommon.model.dto.UserDTO;
import com.zzc.keleapiCommon.service.InnerInterfaceInfoService;
import com.zzc.keleapiCommon.service.InnerUserInterfaceInfoService;
import com.zzc.keleapiCommon.service.InnerUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

@Slf4j
@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {
    public static final List<String> IP_WHITE_LIST = Arrays.asList("127.0.0.1");
    private static final String INTERFACE_HOST = "http://localhost:8103";
    public static final int RAND_NUM_LENGTH = 5;
    public static final long MAX_MILLISECOND_NUM = 5 * 60 * 1000L;

    @DubboReference
    InnerUserService innerUserService;
    @DubboReference
    InnerInterfaceInfoService innerInterfaceInfoService;
    @DubboReference
    InnerUserInterfaceInfoService innerUserInterfaceInfoService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // a. 参数有效性判断
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        String method = request.getMethod().toString();  // 请求方式
        String source = request.getLocalAddress().getHostName();  // 请求来源地址
        String remote = request.getRemoteAddress().getHostName(); // 请求转发地址
        log.info("请求来源地址：{}，请求转发地址：{}", source, remote);

        ServerHttpResponse response = exchange.getResponse();
        if(!IP_WHITE_LIST.contains(source)) { // 白名单查询
            response.setStatusCode(HttpStatus.FORBIDDEN); // 返回401，无权限forbidden
            return response.setComplete();
        }

        // b. api调用鉴权，需要调用UserFeignService
        HttpHeaders headers = request.getHeaders();
        String accessKey = headers.getFirst("accessKey");
        String randNum = headers.getFirst("randNum");
        String timeStamp = headers.getFirst("timeStamp");
        String sign = headers.getFirst("sign");
        UserDTO userDTO = innerUserService.getInvokeUser(accessKey); // 远程调用
        if(
                userDTO == null ||
                randNum.length() < RAND_NUM_LENGTH ||
                Math.abs(System.currentTimeMillis() - Long.parseLong(timeStamp)) > MAX_MILLISECOND_NUM ||
                !sign.equals(genSign(accessKey, randNum, timeStamp, userDTO.getSecretKey()))
        ) {
            response.setStatusCode(HttpStatus.FORBIDDEN); // 返回401，无权限forbidden
            return response.setComplete();
        }

        // c. 判断接口是否可以调用，并返回状态码和响应体内容，用于流程中判断与日志记录
        String url = INTERFACE_HOST + path;
        InterfaceInfoDTO interfaceInfoDTO = innerInterfaceInfoService.getInterfaceInfoDTO(url, method);
        if(interfaceInfoDTO == null) {
            response.setStatusCode(HttpStatus.NOT_FOUND); // 接口不存在
            return response.setComplete();
        }

        log.info("当前接口可以调用 ==> {}", interfaceInfoDTO);
        // d. 同步次数统计。
        return handleResponse(exchange, chain, interfaceInfoDTO.getId(), userDTO.getId());
    }

    private String genSign(String accessKey, String randNum, String timeStamp, String secretKey) {
        return new Digester(DigestAlgorithm.SHA256).digestHex(accessKey + randNum + timeStamp + secretKey);
    }

    /**
     * 线程阻塞调用
     * @param exchange
     * @param chain
     * @param interfaceInfoId
     * @param userId
     * @return
     */
    public Mono<Void> handleResponse(ServerWebExchange exchange, GatewayFilterChain chain, long interfaceInfoId, long userId) {

        FutureTask<Mono<Void>> futureTask = new FutureTask<>(() -> {
            try {
                innerUserInterfaceInfoService.invokeCount(interfaceInfoId, userId);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return chain.filter(exchange);
        });
        Thread thread = new Thread(futureTask);
        thread.start();
        try {
            thread.join();
            return futureTask.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 处理响应
     *
     * @param exchange
     * @param chain
     * @return
     */
    public Mono<Void> handleResponse_expired(ServerWebExchange exchange, GatewayFilterChain chain, long interfaceInfoId, long userId) {
        try {
            ServerHttpResponse originalResponse = exchange.getResponse();
            // 缓存数据的工厂
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            // 拿到响应码
            HttpStatus statusCode = originalResponse.getStatusCode();
            if (statusCode == HttpStatus.OK) {
                // 装饰，增强能力
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
                    // 等调用完转发的接口后才会执行
                    @Override
                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                        log.info("body instanceof Flux: {}", (body instanceof Flux));
                        if (body instanceof Flux) {
                            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                            // 往返回值里写数据
                            // 拼接字符串
                            return super.writeWith(
                                    fluxBody.map(dataBuffer -> {
                                        // 7. 调用成功，接口调用次数 + 1 invokeCount
                                        try {
                                            innerUserInterfaceInfoService.invokeCount(interfaceInfoId, userId);
                                        } catch (Exception e) {
                                            log.error("invokeCount error", e);
                                        }
                                        byte[] content = new byte[dataBuffer.readableByteCount()];
                                        dataBuffer.read(content);
                                        DataBufferUtils.release(dataBuffer);//释放掉内存
                                        // 构建日志
                                        StringBuilder sb2 = new StringBuilder(200);
                                        List<Object> rspArgs = new ArrayList<>();
                                        rspArgs.add(originalResponse.getStatusCode());
                                        String data = new String(content, StandardCharsets.UTF_8); //data
                                        sb2.append(data);
                                        // 打印日志
                                        log.info("响应结果：" + data);
                                        return bufferFactory.wrap(content);
                                    }));
                        } else {
                            // 8. 调用失败，返回一个规范的错误码
                            log.error("<--- {} 响应code异常", getStatusCode());
                        }
                        return super.writeWith(body);
                    }
                };
                // 设置 response 对象为装饰过的
                return chain.filter(exchange.mutate().response(decoratedResponse).build());
            }
            return chain.filter(exchange); // 降级处理返回数据
        } catch (Exception e) {
            log.error("网关处理响应异常" + e);
            return chain.filter(exchange);
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
